// 服务端程序
const http = require("http");
const fs = require("fs");
const path = require("path");
const { URL } = require("url");
const { json } = require("stream/consumers");

function myRouter(myUrl, res) {
    if (myUrl.pathname == "/") {
        readPage(res)
    } else if (myUrl.pathname.indexOf(".png") != -1 || myUrl.pathname.indexOf(".jpg") != -1) {
        readImg(res);
    } else if (myUrl.pathname == "/getList") {
        sendData(res);
    }
}

//响应页面 读取网页文件
function readPage(res) {
    let filePath = path.join(__dirname, "index.html");
    let fileContent = fs.readFileSync(filePath);
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end(fileContent)
}

//相应图片
function readImg(res) {
    let filePath = path.join(__dirname, "icon.png");
    let fileContent = fs.readFileSync(filePath);
    res.writeHead(200, { "Content-Type": "image" });
    res.end(fileContent)
}

//事件处理
function formatTime(timer) {
    let obj = new Date(timer);
    let year = obj.getFullYear();
    let month = obj.getMonth() + 1;
    let date = obj.getDate();
    return year + "-" + month + "-" + date;
}
//post
function sendData(res) {
    let dataList = [];
    let dirPath = path.join(__dirname, "fileDir");
    const fileList = fs.readdirSync(dirPath);
    // console.log(fileList)
    fileList.forEach(file => {
        let fileObj = {};
        // const childPath = `${filePath}/${file}`;
        let childPath = path.join(dirPath, `${file}`);
        let statObj = fs.statSync(childPath);
        fileObj["fileType"] = statObj.isFile() ? "file" : "folder";
        fileObj["fileName"] = `${file}`;
        fileObj["fileSize"] = statObj.size;
        fileObj["fileTime"] = formatTime(statObj.birthtimeMs);
        dataList.push(fileObj);
    })
    console.log(dataList);
    dataList = JSON.stringify(dataList);
    console.log(dataList);
    res.end(dataList);
}


http.createServer((req, res) => {
    let myUrl = new URL(req.url, "http://localhost:8081/")
    // console.log(myUrl);//myUrl的pathname不同
    myRouter(myUrl, res);
}).listen(8081);
console.log("server is listening 8081")
